
import requests
from typing import Dict, Any, Optional
class BotClient:
    def __init__(self, base_url: str = "http://127.0.0.1:3000", token: str = "221300"):
        """
        初始化客户端
        :param base_url: 服务基础地址
        :param token: 授权 token
        """
        self.base_url = base_url.rstrip("/")  # 去掉末尾斜杠
        self.token = token
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {self.token}',
            'Content-Type': 'application/json'
        })

    def post(self, endpoint: str, data: Dict = None) -> Optional[Dict[Any, Any]]:
        """
        内部方法：发送 POST 请求
        """
        url = f"{self.base_url}{endpoint}"
        data = data or {}
        
        try:
            response = self.session.post(url, json=data, timeout=10)
            if response.status_code == 200:
                return response.json()
            else:
                print(f"[{response.status_code}] {response.text}")
                return None
        except Exception as e:
            print(f"请求异常: {e}")
            return None

    def __enter__(self):
        return self  

    def __exit__(self, exc_type, exc_val, exc_tb):
      
        self.session.close()  
        print("关闭连接")
        if exc_type is not None:
            print(f"异常类型: {exc_type}")
            print(f"异常值: {exc_val}")
        return False  